import * as ReqFormAction from './actions/reqForm'
import * as ReqAction from './actions/req'
import * as formUtil from './util/formUtil'
import Immutable from 'immutable'

jQuery.fn.extend({
    bindPropertyChange: function(funobj){
        return this.each(function () {
            var thisid = jQuery(this).attr('id');
            WfForm.addPropertyChangeFn(thisid, funobj);
        });
    }
});

export const WfForm = {
    __propertyChangeFnObj: {},
    __detailFieldChangeFnObj: {},
    getReqFormState: function(){
        return window.store_e9_workflow.getState().workflowReqForm;
    },
    getReqState:function(){
    	return  window.store_e9_workflow.getState().workflowReq;
    },
    addPropertyChangeFn: function(key, funobj){
        if(!key || key.indexOf("field") === -1)
            return;
        let fnArr = this.__propertyChangeFnObj[key];
        if (!!!fnArr) {
            fnArr = new Array();
            this.__propertyChangeFnObj[key] = fnArr;
        }
        fnArr.push(funobj);
    },
    /**
     * 字段值变化绑定事件
     * @params fieldMark(String) 绑定字段标示串，明细字段带下划线标示
     */
    bindFieldChangeEvent: function(fieldMarkStr, funobj){
        !!fieldMarkStr && fieldMarkStr.split(",").map(fieldMark =>{
            this.addPropertyChangeFn(fieldMark, funobj);
        });
    },
    /**
     * 明细字段值变化绑定事件，绑定后对新添加的行也生效
     * @params fieldMark(String) 绑定的明细字段标示串，不带下划线标示
     */
    bindDetailFieldChangeEvent: function(fieldMarkStr, funobj){
        const reg = /^field\d+$/;
        !!fieldMarkStr && fieldMarkStr.split(",").map(key =>{
            if(!key || !reg.test(key))
                return "";
            let fnArr = this.__detailFieldChangeFnObj[key];
            if (!!!fnArr) {
                fnArr = new Array();
                this. __detailFieldChangeFnObj[key] = fnArr;
            }
            fnArr.push(funobj);
        });
    },
    /**
     * 获取字段信息
     */
    getFieldInfo: function(fieldid){
        const fieldInfo = formUtil.getFieldInfoObj(this.getReqFormState(), fieldid);
        return fieldInfo == null ? null : fieldInfo.toJS();
    },
    /**
     * 获取字段当前的字段属性
     */
    getFieldCurViewAttr: function(fieldMark){
        const formState = this.getReqFormState();
        const fieldid = fieldMark.indexOf("_")>-1 ? fieldMark.substring(5,fieldMark.indexOf("_")) : fieldMark.substring(5);
        const tableMark = formUtil.getBelTableMark(formState, fieldid);
        if(!tableMark)
            return -1;
        const conf = formState.get("conf");
        const fieldObj = conf.getIn(["tableInfo", tableMark, "fieldinfomap", fieldid]);
        let fieldVar = formState.hasIn(["variableArea",fieldMark]) ? formState.getIn(["variableArea",fieldMark]) : Immutable.fromJS({});
        //是否是已有明细数据行
        if(tableMark.indexOf("detail_")>-1){
            const rowIndex = fieldMark.indexOf("_")>-1 ? fieldMark.substring(fieldMark.indexOf("_")+1) : -1;
            const detailRowData = formState.getIn(["detailData", tableMark, "rowDatas", `row_${rowIndex}`]) || Immutable.fromJS({});
            fieldVar = fieldVar.set("isDetailExistField", parseInt(detailRowData.get("keyid")||0) > 0);
        }
        const params = window.store_e9_workflow.getState().workflowReq.get("params");
        return formUtil.getFieldCurViewAttr(fieldObj, tableMark, conf, fieldVar, params);
    },
    /**
     * 获取字段值
     * @params fieldMark(String)    字段标示,主表字段：field110，明细行字段需加上行标示：field110_4
     */
    getFieldValue: function(fieldMark){
        if(fieldMark.indexOf("field") === -1)
            return null;
        const formState = this.getReqFormState();
        const index = fieldMark.indexOf("_");
        const fieldid = index>-1 ? fieldMark.substring(5, index) : fieldMark.substring(5);
        const rowIndex = index>-1 ? fieldMark.substring(index+1) : -1;
        return formUtil.getFieldValue(formState, fieldid, rowIndex, null, false);
    },
    /**
     * 获取字段值对象
     */
    getFieldValueObj: function(fieldMark){
        if(fieldMark.indexOf("field") === -1)
            return null;
        const formState = this.getReqFormState();
        const index = fieldMark.indexOf("_");
        const fieldid = index>-1 ? fieldMark.substring(5, index) : fieldMark.substring(5);
        const rowIndex = index>-1 ? fieldMark.substring(index+1) : -1;
        let valueObj = formUtil.getFieldValueObj(formState, fieldid, rowIndex, "");
        if(Immutable.Map.isMap(valueObj))
            valueObj = valueObj.toJS();
        return valueObj;
    },
    /**
     * 获取浏览按钮字段对应的显示值
     */
    getBrowserShowName: function(fieldMark,splitChar){
        if(fieldMark.indexOf("field") === -1)
            return "";
        if(typeof splitChar === "undefined" || splitChar === "")
            splitChar = ",";
        let showname = "";
        const valueObj = this.getFieldValueObj(fieldMark);
        if(valueObj !== null && "specialobj" in valueObj){
            valueObj.specialobj.map((v,index) =>{
                if(index !== 0)
                    showname += splitChar;
                showname += v.name;
            });
        }
        return showname;
    },
    /**
     * 修改字段值，适用范围(单行文本、多行文本、选择框、浏览框、check框(0/1))
     * @params valueInfo(JSON)    非浏览框格式为：{value:"修改后的值"}，浏览按钮字段格式为：{value:"1,2,3",specialobj:[{id:"1",name:"张三"},{id:"2",name:"李四"},{id:"3",name:"王五"}...]}
     */
    changeFieldValue: function(fieldMark, valueInfo){
        this.changeSingleField(fieldMark, valueInfo, null)
    },
    /**
     * 修改字段只读/可编辑/必填/隐藏属性，此接口优先级低于标准功能显示属性联动(即设置了显示属性联动的可能覆盖此设置)
     * @params viewAttr(int)  1(变更为只读)/2(变更为可编辑)/3(变更为必填)/4(字段标签及名称都隐藏，同时不校验必填)
     */
    changeFieldAttr: function(fieldMark, viewAttr){
        this.changeSingleField(fieldMark, null, {viewAttr});
    },
    /**
     * 修改单个字段属性，修改值同时修改显示属性
     * @params valueInfo(obj) 可为空，变更的字段值
     */
    changeSingleField: function(fieldMark, valueInfo, variableInfo){
        workflowDoAction(ReqFormAction.changeSingleFieldValue, fieldMark, valueInfo, variableInfo);
    },
    /**
     * 批量修改多个字段值及属性
     * @params changeDatas(obj)  格式{field110:{value:"11"},field111_1:{value:"22"}
     * @params changeVariable(obj) 格式{field110:{viewAttr:1},field111_1:{viewAttr:3}}
     */
    changeMoreField: function(changeDatas={}, changeVariable={}){
        workflowDoAction(ReqFormAction.changeMoreFieldData, changeDatas, changeVariable);
    },
    /**
     * 移除选择框字段选项
     */
    removeSelectOption: function(fieldMark, optionKeys){
        const formState = this.getReqFormState();
        let filterOptionRange = formState && formState.getIn(["variableArea", fieldMark, "filterOptionRange"]);
        if(!filterOptionRange)
            filterOptionRange = Immutable.fromJS([]);
        filterOptionRange = filterOptionRange.concat(Immutable.fromJS(optionKeys.split(",")));
        this.changeSingleField(fieldMark, null, {filterOptionRange: filterOptionRange});
    },
    /**
     * 控制选择框字段选项范围
     */
    controlSelectOption: function(fieldMark, optionKeys){
        const optionRange = Immutable.fromJS(optionKeys.split(","));
        this.changeSingleField(fieldMark, null, {optionRange: optionRange, filterOptionRange:null});
    },
    /**
     * 添加明细行
     * @params detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
     * @params initAddRowData(JSON) 新增行设置的初始值，可不传；格式为{field110:{value:"11"},field112:{value:"22"},...},注意key不带下划线标示
     */
    addDetailRow: function(detailMark, initAddRowData={}){
         workflowDoAction(ReqFormAction.addDetailRow, detailMark, initAddRowData);
    },
    /**
     * 删除明细行,没有提示删除的确认框(会清空明细已选情况)
     * @params detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
     * @params rowIndexMark(String) 明细行标示，全部选中:all,选中部分："1，2，3"
     */
    delDetailRow: function(detailMark, rowIndexMark){
        this.checkDetailRow(detailMark, rowIndexMark, true);
        workflowDoAction(ReqFormAction.delDetailRow, detailMark);
    },
    /**
     * 选中明细行
     * @params detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
     * @params rowIndexMark(String) 明细行标示，全部选中:all,选中部分："1，2，3"
     * @params needClearBeforeChecked(Boolean) 是否需要清除已有选中，默认为false
     */
    checkDetailRow: function(detailMark, rowIndexMark, needClearBeforeChecked){
        if(needClearBeforeChecked === true) //清除已选
            workflowDoAction(ReqFormAction.setDetailRowChecked, detailMark, "all", false);
        workflowDoAction(ReqFormAction.setDetailRowChecked, detailMark, rowIndexMark, true);
    },
    /**
     * 获取明细所有行标示，逗号分隔
     * @params detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
     */
    getDetailAllRowIndexStr: function(detailMark){
        const formState = this.getReqFormState();
        return formUtil.getDetailAllRowIndexStr(formState, detailMark);
    },
    /**
     * 根据字段id获取对应的明细行数据库key值
     */
    getDetailRowKey: function(fieldMark){
        const formState = this.getReqFormState();
        if(fieldMark.indexOf("field") === -1 || fieldMark.indexOf("_") === -1)
            return -1;
        const fieldid = fieldMark.substring(5,fieldMark.indexOf("_"));
        const rowIndex = fieldMark.substring(fieldMark.indexOf("_")+1);
        const tableMark = formUtil.getBelTableMark(formState, fieldid);
        const detailRowData = formState.getIn(["detailData", tableMark, "rowDatas", `row_${rowIndex}`]) || Immutable.fromJS({});
        return detailRowData.has("keyid") ? parseInt(detailRowData.get("keyid")) : -1;
    },
    /**
     * 控制明细点添加是否复制指定行记录(不复制附件上传字段)
     * @params detailMark(String) 明细表标示，明细1就是detail_1，以此递增类推
     * @params needCopy(Boolean)  true需要复制，false取消复制
     */
    setDetailAddUseCopy: function(detailMark, needCopy){
        if(detailMark.indexOf("detail_") === -1 || typeof needCopy !== "boolean")
            return;
        const changeInfo = {[`${detailMark}_copyCfg`]: needCopy};
        workflowDoAction(ReqFormAction.controlVariableArea, changeInfo);
    },
    /**
     * 文本字段可编辑状态，当值为空显示默认灰色提示信息，鼠标点击输入时消失
     */
    setTextFieldEmptyShowContent: function(fieldid, showContent){
        if(!fieldid || fieldid.indexOf("field") === -1)
            return;
        const mergeInfo = {"textFieldEmptyShowContent": {[fieldid]: showContent}};
        workflowDoAction(ReqFormAction.controlVariableArea_merge, mergeInfo);
    },
    /**
     * 浏览按钮请求数据接口，支持传输自定义参数，联想输入及弹窗都支持
     */
    appendBrowserDataUrlParam: function(fieldMark, jsonParam){
        const fieldid = fieldMark.indexOf("_")>-1 ? fieldMark.substring(5,fieldMark.indexOf("_")) : fieldMark.substring(5);
        const fieldInfo = this.getFieldInfo(fieldid);
        if(fieldInfo && fieldInfo.htmltype === 3){  //限制浏览框类型
            this.changeSingleField(fieldMark, null, {customDataParam: jsonParam});
        }
    },
    /**
     * 复写浏览按钮属性
     */
    overrideBrowserProp: function(fieldMark, jsonParam){
        const fieldid = fieldMark.indexOf("_")>-1 ? fieldMark.substring(5,fieldMark.indexOf("_")) : fieldMark.substring(5);
        const fieldInfo = this.getFieldInfo(fieldid);
        if(fieldInfo && fieldInfo.htmltype === 3){  //限制浏览框类型
            this.changeSingleField(fieldMark, null, {customBrowserProp: jsonParam});
        }
    },
    /**
     * 控制表单按钮是否点击
     * @param flag : true 按钮全部置灰不可操作 false 恢复按钮可操作状态
     */
    controlBtnDisabled: function(isDisabled){
        workflowDoAction(ReqAction.updateFormLoading, isDisabled);
    },
    
    /**
     * 更新提交参数
     * @param {Object} updateInfo
     */
    updateSubmitInfo:function(updateInfo){
    	workflowDoAction(ReqAction.updateSubmitParams, updateInfo);
    },
    /**
     * 获取submitParams 中的参数值
     * @param {Object} key
     */
    getSubmitInfoByKey:function(key){
    	return this.getReqState().getIn(["submitParams",key])||"";
    },
    /**
     * 附件下载
     * @param {Object} downloadUrl
     */
    setFileDownload:function(downloadUrl){
    	workflowDoAction(ReqAction.setFileDownloadUrl, downloadUrl);
    },
    downLoadFile: function(fileid){
        const params = this.getReqState().get("params");
        let url = "/weaver/weaver.file.FileDownload?fileid="+fileid+"&download=1";
        if(params)
            url += "&requestid="+params.get("requestid")+"&authStr="+params.get("authStr")+"&authSignatureStr="+params.get("authSignatureStr")
                +"&f_weaver_belongto_userid="+params.get("f_weaver_belongto_userid")+"&f_weaver_belongto_usertype="+params.get("f_weaver_belongto_usertype");
        this.setFileDownload(url);
    }
}

window.WfForm = WfForm;


/**
 * 重写E8浏览按钮赋值的函数
 * @param fieldMark  字段标示
 * @param isMustInput 无效参数
 * @param data 修改的数据，JSON含id及name
 * @param _options 修改方式，替换/追加值
 */
window._writeBackData = function(fieldMark, isMustInput, data, _options){
    try{
        if(typeof data !== "object")
            return;
        const _id = data.id || "";
        const _name = data.name || "";
        const options = jQuery.extend({replace:false,isSingle:true}, _options);
        let value = "";
        let specialobj = new Array();
        if(options.isSingle || options.replace){    //替换值
            value = _id;
            if(value !== "")
                specialobj.push({id:_id, name:_name});
        }else{  //追加值
            if(_id === "" || _name === "")
                return;
            let curBrowValue = WfForm.getFieldValueObj(fieldMark) || {};
            value = (curBrowValue.value || "") + "," + _id;
            specialobj = (curBrowValue.specialobj || new Array()).concat([{id:_id, name:_name}]);
        }
        WfForm.changeFieldValue(fieldMark, {value:value, specialobj:specialobj});
    }catch(e){
        if(window.console)  console.log("_writeBackData Exception:"+e);
    }
}